package org.apache.flink.connector.jdbc.databases.mysql.dialect;


import java.util.Arrays;
import java.util.stream.Collectors;

public class testUpsertStatement {
    // String tableName, String[] fieldNames, String[] uniqueKeyFields
//    private static String[] fieldNames;
//    private static String tableName;
//    private static String[] keyFields;

    public static void main(String[] args) {
        
//        String[] fieldNames  = '["id", "name", "email", "ts", "field1"]';
        String[] fieldNames = {"id", "name", "email", "ts", "field1", "field_2", "__field_3__"};
        String tableName = "tb1";
        String[] keyFields = {"id", "name", "email", "ts", "field1"};
        getUpsertStatement(fieldNames,tableName,keyFields);
    }

    private static String getUpsertStatement(String[] fieldNames, String tableName, String[] keyFields) {
        String updateClause =
                Arrays.stream(fieldNames)
                        .map(f -> quoteIdentifier(f) + "=VALUES(" + quoteIdentifier(f) + ")")
                        .collect(Collectors.joining(", "));

        String insert = getInsertIntoStatement(tableName, fieldNames);
        String value = insert + " ON DUPLICATE KEY UPDATE " + updateClause;
        
        System.out.println(value);

        return value;
    }

    private static String getInsertIntoStatement(String tableName, String[] fieldNames) {
        String columns =
                Arrays.stream(fieldNames)
//                        .map(f::quoteIdentifier)
                        .collect(Collectors.joining(", "));
        //placeholders：":id, :name, :email, :ts, :field1, :field_2, :__field_3__"
        String placeholders =
                Arrays.stream(fieldNames).map(f -> ":" + f).collect(Collectors.joining(", "));


        return "INSERT INTO "
                + quoteIdentifier(tableName)
                + "("
                + columns
                + ")"
                + " VALUES ("
                + placeholders
                + ")";
    }

    private static String quoteIdentifier(String identifier) {
        return "`" + identifier + "`";
    }
}
